package com.zxb.core.util;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.List;

/**
 * @author Zxb
 */
@Component
public class PdfUtil {

    @SneakyThrows
    public static void create(String msg, OutputStream out) {
        Document document = new Document();
        PdfWriter.getInstance(document, out);
        document.open();
        BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font font = new Font(baseFont, 12, Font.NORMAL);
        Paragraph paragraph = new Paragraph(msg, font);
        document.add(paragraph);
        document.close();
    }

    @SneakyThrows
    public static void merge(List<File> pdfFileList, OutputStream out) {
        Document document = new Document();
        PdfCopy copy = new PdfCopy(document, out);
        document.open();
        for (File pdfFile : pdfFileList) {
            // 创建pdf读取器
            PdfReader reader = new PdfReader(Files.newInputStream(pdfFile.toPath()));
            // 获取PDF文件总页数
            int n = reader.getNumberOfPages();
            for (int i = 1; i <= n; i++) {
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader, i);
                copy.addPage(page);
            }
        }
        document.close();
    }
}
